package org.grow.yc.controller;

import org.apache.tomcat.util.security.MD5Encoder;
import org.grow.yc.dao.EmployeeMapper;
import org.grow.yc.entity.Employee;
import org.grow.yc.exception.MissTargetException;
import org.grow.yc.filter.AuthInterceptor;
import org.grow.yc.service.JwtService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;


import java.util.HashMap;

/**
 * @Author: xwg
 * @CreateDate: 2024/9/29
 */

@RequestMapping("/pwd")
@RestController
public class PwdLoginController {
    @Autowired
    private JwtService jwtService;
    @Autowired
    private EmployeeMapper employeeMapper;

    @PostMapping("/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password){
        Employee fromDB = employeeMapper.findByUsername(username);
        if(fromDB == null){
            throw new MissTargetException("当前用户名不存在");
        }

        String pwdFromDB = fromDB.getPassword();
//        把明文密码加密 ，比较加密后的两个密码是否相同
//        不要试图解密  hash
        String fromFront = this.pwdEncode(password);

        if(!pwdFromDB.equals(fromFront)){
            throw  new MissTargetException("用户名密码不一致");
        }


//        String UID= "";
//        if(username.equals("zhangsan")){
//            UID = "zhangsan001";
//        }else if( username.equals("lisi")){
//            UID = "lisi007";
//        }else if( username.equals("wangwu")){
//            UID="wangwu005";
//        }else{
//            throw new RuntimeException("Invalid username");
//        }
//        jwt 需要在此对UID进行加密生成token 返回token
        HashMap<String, Object> map = new HashMap<>();
        map.put("UID",fromDB.getUID());
//        签发token
        String token = jwtService.createToken(map);
        return token;
    }


    private String pwdEncode(String mingwen){
        return mingwen;
    }
    @GetMapping("/currentUser")
    public String currentUser(){
//
     String currentUser = AuthInterceptor.getCurrentUser();
        return currentUser;
    }
}
